/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-04-20
 * Time: 10:57
 */
class MyBlockingQueue {
    private String[] data = null;
    private int head;
    private int tail;
    private int size;
    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            //while 目的:二次验证
            while (size >= data.length) {
                //wait不一定是被notify唤醒也会有可能是被interrupt中断唤醒的因此使用while可以避免wait被提前唤醒，
                // 确保一定是因为有其他线程take之后notify了当前wait
                this.wait();
            }
            data[tail++] = elem;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this) {
            //while 目的:二次验证
            while (size == 0) {
                //wait不一定是被notify唤醒也会有可能是被interrupt中断唤醒的因此使用while可以避免wait被提前唤醒，
                // 确保一定是因为有其他线程put之后notify了当前wait
                this.wait();
            }
            String ret = data[head++];
            if (head >= data.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}
public class Demo44 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread producer = new Thread(() -> {
            int n = 0;
            while(true) {
                try {
                    queue.put(n + "");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("生产元素 " + n);
                n++;
            }
        });
        Thread consumer = new Thread(() -> {
            String ret = null;
            while(true) {
                try {
                    ret = queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消耗元素 " + ret);
            }
        });
        producer.start();
        consumer.start();
    }
}
